<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <!-- 搜索表单 -->
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
    >
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        :load-on-created="false"
        flex-table
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :export-config="{ fileName: '入款记录数据', datasource: exportSource }"
        :print-config="{ datasource: exportSource }"
        cache-key="orderPayLogTable"
      >
        <template #toolbar>
          <el-button
            v-show="shengyuTotalPrice > 0"
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建登记
          </el-button>
        </template>
        <template #pay_method="{ row }">
          <dict-data :code="'pay_method'" v-model="row.pay_method" type="tag" />
        </template>
      </ele-pro-table>
    </ele-card>

    <ele-image-viewer
      v-model="showImageViewer"
      :urlList="viewerImages"
      :initialIndex="viewerIndex"
      :infinite="false"
      :hide-on-click-modal="true"
    />
    <!-- 新增 -->
    <pay-log-edit
      action="add"
      :data="current"
      :totalPrice="shengyuTotalPrice"
      :orderNumber="orderNumber"
      v-model="showAdd"
      @done="
        () => {
          reload();
          reloadPayLog();
        }
      "
    />
    <!-- 修改 -->
    <!-- <pay-log-edit
      action="edit"
      :data="current"
      :orderNumber="orderNumber"
      v-model="showEdit"
      @done="reload"
    /> -->
  </ele-page>
</template>

<script setup>
import { computed, ref, watch } from "vue";

import PayLogEdit from "./components/edit.vue";
import { pagePayLogs, removePayLogs, listPayLogs } from "@/api/order/pay-log";
import { useOperator } from "@/hooks/operator";
import { PlusOutlined } from "@/components/icons";
import { add, reduce } from "@/utils/decimal.js";

import { useTable } from "@/hooks/useTable";
import { useModal } from "@/hooks/useModal";

defineOptions({ name: "SystemPayLog" });
const emit = defineEmits(["reload"]);

const props = defineProps({
  orderNumber: {
    type: String,
    default: "",
  },
  totalPrice: {
    type: Number,
    default: 0,
  },
});
watch(
  () => props.orderNumber,
  (newVal) => {
    if (newVal) {
      reload({
        order_number: newVal,
      });
    }
  },
);

const shengyuTotalPrice = computed(() => {
  if (loading.value) return null;
  if (!Array.isArray(datasourceData.value) || !datasourceData.value.length)
    return props.totalPrice;
  const paidTotal = datasourceData.value.reduce(
    (sum, item) => add(sum, item?.pay_price || 0),
    0,
  );
  console.log("paidTotal", paidTotal, "totalPrice", props.totalPrice);
  const result = reduce(props.totalPrice, paidTotal);
  return result;
});

/** 是否打开图片预览 */
const showImageViewer = ref(false);

/** 图片预览数据 */
const viewerImages = ref([]);

/** 图片预览初始位置 */
const viewerIndex = ref(0);

/** 表格列配置 */
const columns = ref([
  {
    prop: "pay_price",
    label: "入款金额",
    width: 170,
    slot: "pay_price",
  },

  {
    prop: "pay_method",
    label: "支付方式",
    minWidth: 120,
    slot: "pay_method",
  },
  {
    prop: "pay_date",
    label: "支付时间",
    minWidth: 120,
  },
  {
    prop: "pay_note",
    label: "支付备注",
    minWidth: 120,
  },
  {
    prop: "created_at",
    label: "创建时间",
    minWidth: 120,
  },
]);

/** 导出和打印全部数据的数据源 */
const exportSource = ({ where, orders }) => {
  return listPayLogs({ ...where, ...orders });
};

const {
  loading,
  pagination,
  tableRef,
  datasource,
  reload,
  current,
  selections,
  datasourceData,
} = useTable({
  getPages: pagePayLogs,
  beforeQuery: (params) => {
    console.log("查询参数:", params); // 调试用，实际不需要这一行
    return {
      ...params,
      ...params.where,
    };
  },
});

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: async () => {
    current.value = null; // 新增时重置数据
    // if (!props.dict_ids) {
    //   throw new Error("请先选择字典");
    // }
  },
});
/** 删除 */
// 替换原有的remove方法
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      confirmText: "确定要删除{%s}这些数据吗?",
      api: removePayLogs,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
  },
  selections,
  reload,
  idField: "id",
  idName: "business.company_name",
});

const reloadPayLog = () => {
  emit("reload");
};
</script>
